package com.fstart.sys.controller;

import com.alibaba.fastjson2.JSON;
import com.fstart.common.Result;
import com.fstart.sys.entity.Diary;
import com.fstart.sys.entity.User;
import com.fstart.sys.service.IDiaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.SimpleTimeZone;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Xibing
 * @since 2023-05-04
 */
@RestController
@RequestMapping("/sys/diary")
public class DiaryController {
    @Autowired
    private IDiaryService diaryService;

    // redis
    @Autowired
    private RedisTemplate redisTemplate;

    // 更具日期查询当前的日记
    @GetMapping("/getDiary")
    public Result<?> getDiaryByDate(@RequestParam(value = "userId") Integer userId,
                                    @RequestParam(value = "createTime") String createTime) {
        // 现在redis中查找没有则到数据库中查找
        String RedisDiaryKey = "Diary-" + createTime + "-" + userId;
        Object obj = redisTemplate.opsForValue().get(RedisDiaryKey);
        Diary RedisDiaryData = JSON.parseObject(JSON.toJSONString(obj), Diary.class);

        if (RedisDiaryData.getDiary() == null && RedisDiaryData.getId() == null) {
            System.out.println("redis中没有数据");
            System.out.println(RedisDiaryKey);

            Diary diary = new Diary();
            diary.setUserId(userId);
            diary.setCreateTime(LocalDateTime.parse(createTime));

            Diary data = diaryService.getDiaryByDate(diary);
            if (data != null) {
                redisTemplate.opsForValue().set(RedisDiaryKey, data, 2 * 60, TimeUnit.MINUTES);
            }
            return Result.success(data);
        }
        return Result.success(RedisDiaryData);


    }

    // 添加或者更新日记
    @PostMapping("/addDiary")
    public Result<?> saveOrUpdate(@RequestBody Diary diary) {
        // 用户id和日期查询
        diary.setUpdateTime(LocalDateTime.now());

        Diary diaryByDate = diaryService.getDiaryByDate(diary);
        if (diaryByDate == null) {
            // 没有则添加
            diaryService.save(diary);
        } else {
            diary.setId(diaryByDate.getId());
            // 有则修改
            diaryService.updateById(diary);
        }

        // 更行Redis中的数据
        //key
        String RedisDiaryKey = "Diary-" + diary.getCreateTime() + "-" + diary.getUserId();
        redisTemplate.opsForValue().set(RedisDiaryKey, diary);

        return Result.success("操作成功!");
    }
}
